﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MobiShop.Models;

namespace MobiShop
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        // hoàng
        // kiểm tra cookies trên máy người dùng, nếu có ghi nhớ cookies thì tự động đăng nhập lại
        // cho họ
        protected void Session_Start(object sender, EventArgs e)
        {
            if (Request.Cookies["username"] != null && Request.Cookies["password"] != null)
            {
                string username = Request.Cookies["username"].Value;
                string password = Request.Cookies["password"].Value;

                if (0 < username.Length && username.Length <= 50 &&
                    password.Length == 32) 
                {
                    Account account = AccountModels.LoginWithMd5Password(username, password);
                    if (AccountModels.IsAllowAccount(account))
                        Session["Account"] = account;
                    //if (account == null) // cookies không hợp lệ, hủy cookies
                    //{
                    //    AccountModels.WriteCookies(null, Response);
                    //}
                }
            }
            // tạo cho người dùng 1 giỏ hàng 
            Session["ShoppingBasket"] = new ShoppingBasket();
        }
    }
}